var app = getApp()
var util = require("../../utils/util.js")
var tuanModel = require("../../model/tuanModel.js")
var shopModel = require("../../model/shopModel.js")
var userUtil = require("../../utils/userUtil.js")
var timeUtil = require("../../utils/timeUtil.js")
var wxParse = require('../../plugins/wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sales: 0,
    showMoreTuan: false,
    tuanRecords: [], //凑团列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      sales: options.sales
    })
    this.init();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  /**
   * 监听页面注销
   */
  onUnload: function() {
    clearInterval(this.data.interval)
  },
  init() {
    var tuan = app.data.tempTuan
    var data = {
      id: tuan.productId,
      type: tuan.productType
    }
    var that = this
    util.showLoading("加载中")
    shopModel.getGoodsInfo(data, res => {
      wx.hideLoading()
      if (res.status == 1) {
        return
      }
      wxParse.wxParse('info', 'html', res.data.html, that, 5);
      that.setData({
        tuan: tuan,
        goods: res.data
      })
    })
    //凑团
    if (tuan.makeUp == 1) return
    tuanModel.getTuanRecordList(tuan.id, res => {
      if (res.status == 1) return
      console.log(res)
      var list = res.data
      list = handleTuanRecord(list)
      that.setData({
        tuanRecords: list
      })
      var interval = setInterval(() => {
        list = handleTuanRecord(list)
        that.setData({
          tuanRecords: list
        })
      }, 1000)
      that.setData({
        interval: interval
      })
    })
  },
  //订单支付页面
  navToOrderPay(e) {
    if (!userUtil.isLogin()) {
      userUtil.toLogin()
      return
    }
    var type = parseInt(e.currentTarget.id)
    var goods = this.data.goods
    goods.num = 1
    if (type == 1) goods.price = this.data.tuan.price
    else goods.price = this.data.tuan.productPrice
    app.data.selectGoods = [goods]
    wx.navigateTo({
      url: '../order_pay/order_pay?type=' + type + "&tuanId=" + this.data.tuan.id,
    })
  },
  //查看更多
  bindMore() {
    this.setData({
      showMoreTuan: true
    })
  },
  //关闭团列表弹窗
  bindCloseMore() {
    this.setData({
      showMoreTuan: false
    })
  },
  navToJoinTuan(e) {
    var id = e.currentTarget.id
    console.log("id", id)
    wx.navigateTo({
      url: '../tuan_join/tuan_join?share=1&trId=' + id,
    })
  }
})

function handleTuanRecord(list) {
  for (var i = 0; i < list.length; i++) {
    list[i].timeStr = timeUtil.formatTime(list[i].validTime)
    list[i].validTime -= 1
    if (list[i].validTime <= 0) {
      list.slice(i, 1)
      i--
    }
  }
  return list
}